/**
 * (c) 2012 Samuel Nelson. All rights reserved
 */

var helpplz = new Array();

// The current querystring. Contains search data
helpplz.querystring = '';
// Whether or not we are currently loading more results. Prevents spamming of
// AJAX requests
helpplz.loading = false;
// Holds the url of the next page of results
helpplz.next = null;
// The container of data we set when we drag a plz emoticon
helpplz.dragData = '';
// Whether our plugin has shown all the results we have available. This prevents
// many requests if the user were to keep scrolling to the bottom of the list
helpplz.shownAllResults = false;
// Our unique id counter
helpplz.uniqueId = 0;
// Whether or not we have loaded the first set of plz accounts. We delay
// loading until the user has interacted with our plugin
helpplz.hasLoadedFirstResults = false;
// Our local storage
helpplz.lstore = new Array();

helpplz.searchCollapsed = false;
helpplz.listCollapsed = false;

// Searches using data from the search form and saves the search to our local
// storage so the user can come back to the results on any page
helpplz.search = function() {
    var search = $('#helpplzExtSearchBox').val();
    var query = $('#helpplzExtSearchForm').serialize();
	helpplz.shownAllResults = false;
	$('#helpplzContent').html('');
	helpplz.lstore['lastQueryString'] = query;
	helpplz_browser.save(helpplz.lstore);
	helpplz.loadNext('http://helpplz.info/browsers/rest.php?' + query);	
	return false;
}

// Attempts to add the plz from data in the add plz form
helpplz.addPlz = function() {
	$('#helpplzAddMsg').text('');
	$('#helpplzAddSpinner').show();
	var plz = $('#helpplzPlzName').val();
	if (plz != '')
	{
		var query = $('#helpplzAddPlzF').serialize();
		$.post('http://helpplz.info/browsers/rest.php',
			query, function(data, textStatus, jqXHR) {
				$('#helpplzAddSpinner').hide();
				if(data.exception)
				{
					$('#helpplzAddMsg').text(data.exception);
				}
				else if(data.response)
				{
					$('#helpplzAddMsg').text(data.response);
				}
				console.log(data);
			}, 'json');
	}
	return false;
}

// Sets up a generic droppable item with the given selector and the given
// callback that will be called when the droppable is dropped on
helpplz.setupDroppable = function(item, callback) {
	$(item).droppable('destroy');
	$(item).droppable({
		drop: function() {
			callback();
		}
	});
}

// Sets up a generic draggable item with the given selector. If fromMyList is
// true the given item should be in the user's account list, false otherwise
helpplz.setupDraggable = function(item, fromMyList) {
	$(item).draggable('destroy');
	$(item).draggable({
		helper: 'clone',
		start: function(event, ui) {
			helpplz.createDropTargets();
			helpplz.dragData = {
				id: $(item).attr('id'),
				name: $(item).attr('title'),
				source: $(item).attr('src'),
				fromMyList: fromMyList
			}
			if (fromMyList)
			{
                // User is dragging one of the accounts in their personalized 
                // list
				helpplz.toggleBottomButtons(true);
				helpplz.setupDroppable('#helpplzDeleteFromList', function(event) {
					var items = helpplz.lstore['myList'];
					var indexToDelete = -1;
					for(var i in items)
					{
						if(items[i].name === helpplz.dragData.name)
						{
							indexToDelete = i;
						}
					}
					items.splice(indexToDelete, 1);
					helpplz.lstore['myList'] = items;
					helpplz_browser.save(helpplz.lstore);
					$('#'+helpplz.dragData.id).remove();
					helpplz.toggleBottomButtons(false);
					if ($('.myListPlz').length == 0)
					{
						$('#helpplzMyListMessage').show();
					}
				});
			}
			else
			{
				$('#myList').css('border', '3px #376F94 dashed');
				$('#myList').css('padding', '0px');
			}
		},
		stop: function() {
			if (fromMyList)
			{
				helpplz.toggleBottomButtons(false);
			}
			else
			{
				$('#myList').css('border', 'none');
				$('#myList').css('padding', '3px');
			}
		},
		drag: function(event, ui) {
			ui.helper.css('z-index', '999');
		}
	});
}

// Loads the next page of results and appends them into our scrollable element
helpplz.loadNext = function(url) {
	helpplz_browser.getJSON(url, function(json) {
		var data = json.data;
		if(data.length == 0)
		{
			helpplz.shownAllResults = true;
		}
		for(i in data)
		{
			var obj = data[i];
			$('#helpplzContent').append('<img class="plz" draggable="true" title="' + obj.Name + '" src="' + obj.Source + '"/>');
		}
		$('.plz').each(function(index, item) {
			helpplz.setupDraggable(item, false);	
		});
		
		helpplz.next = json.next;
		helpplz.loading = false;
	});
}

// Inserts text into the given text field or textarea at the cursor's position
helpplz.insertAtCursor = function(myField, myValue) {
    if (myField.selectionStart || myField.selectionStart == '0') {
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos)
		+ myValue
		+ myField.value.substring(endPos, myField.value.length);
	} else {
		myField.value += myValue;
	}
}

// Creates drop targets on all textareas and the dAmn chat field for
// dropping emoticons
helpplz.createDropTargets = function() {
	$('textarea').each(function(index, item) {
		var area = this;
		helpplz.setupDroppable(item,  function() {
			helpplz.insertAtCursor(area, ':icon' + helpplz.dragData.name + ':');
		});
	});
	$('.damncrc-input').find('input').each(function(index, item) {
		var area = this;
		helpplz.setupDroppable(item,  function() {
			helpplz.insertAtCursor(area, ':icon' + helpplz.dragData.name + ':');
		});
	});
}

// Generates a unique id for dynamically generated elements
helpplz.generateUniqueId = function() {
	helpplz.uniqueId++;
	return helpplz.uniqueId;
}

// Sets up all emoticons on the page and in our plugin for drag and drop into
// textareas and dAmn chat
helpplz.setupAvatarsForDragging = function() {
	$('.avatar').each(function(index, item) {
		helpplz.setupDraggable(item, false);
	});
}

// Toggles the bottom buttons. If showDelete is true shows the delete button
// and hides the add button, otherwise hides the delete button and shows the
// add button
helpplz.toggleBottomButtons = function(showDelete) {
	if(showDelete)
	{
		$('#helpplzDeleteFromList').show('fast');
		$('#helpplzAddPlz').hide('fast');
	}
	else
	{
		$('#helpplzDeleteFromList').hide('fast');
		$('#helpplzAddPlz').show('fast');
	}
	$('#helpplzAddPlzForm').hide('fast');
}

// Expand or collapse
helpplz.toggleSection = function(listOrSearch) {
	if (listOrSearch == 'list')
	{
		if (helpplz.listCollapsed)
		{
			$(
		}
	}
	else if (listOrSearch == 'search')
	{
		
	}
}

// Load our stored plz accounts and start our app
helpplz_browser.load(function(response) {
	helpplz.lstore = response;
	if (helpplz.lstore['lastQueryString'])
		helpplz.querystring = helpplz.lstore['lastQueryString'];
	var alpha = helpplz.querystring.indexOf('alpha=true') >= 0;
	
    // Set up the html we will inject into deviantart
	$('body#deviantART-v7').prepend('<div id="helpplzShower" title="open helpplz">helpplz</div><div id="helpplzExt"></div><div id="pseudodroppable"></div>');
    var html = '<a class="helpplzShowerLink"><img src="http://helpplz.info/images/close.png" title="hide"></a><form id="helpplzExtSearchForm" action="" method="get">';
	html += '<input placeholder="search" type="text" id="helpplzExtSearchBox" name="search" />';
	html += '<input name="helpplzExtSubmit" type="submit" value="search"/>';
	html += '<div class="helpplzSmallLine"><label for="helpplzMatchBeginning">matches beginning</label>';
	html += '<input id="helpplzMatchBeginning" '+(alpha ? 'checked="checked"' : '')+' type="radio" name="alpha" value="true"/>';
	html += '<label for="helpplzMatchAnywhere">anywhere</label><input id="helpplzMatchAnywhere" '+(alpha ? '' : 'checked="checked"')+' type="radio" name="alpha" value="false"/></div></form>';
	html += '<fieldset><legend>search results</legend><div id="helpplzContentParent"><div id="helpplzContent"></div></div></fieldset><fieldset><legend>my list</legend><div id="myList"><span id="helpplzMyListMessage">drag and drop plz accounts here to save to your list</span></div></fieldset>';
	html += '<div id="helpplzDeleteFromList">remove from my list</div><div id="helpplzAddPlzForm"><form id="helpplzAddPlzF" action="" method="post"><input id="helpplzPlzName" size="17" type="text" name="plzName" placeholder="nameofplz"/>.deviantart<input type="submit" value="add"/></form>';
	html += '<img id="helpplzAddSpinner" src="http://helpplz.info/browsers/chrome/ajax-loader.gif"/><span id="helpplzAddMsg"></span></div><div id="helpplzAddPlz">add plz to database</div>';
	html += '<div class="helpplzSmallText">created by ~<a target="parent" href="http://famine-star.deviantart.com/" style="margin-left:0px;">famine-star</a>';
	html += '<form action="https://www.paypal.com/cgi-bin/webscr" method="post" style="display:inline;" target="_blank"><input type="hidden" name="cmd" value="_s-xclick">';
	// The following is code for the paypal donate button
    html += '<input type="hidden" name="encrypted" value="-----BEGIN PKCS7-----MIIHLwYJKoZIhvcNAQcEoIIHIDCCBxwCAQExggEwMIIBLAIBADCBlDCBjjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtQYXlQYWwgSW5jLjETMBEGA1UECxQKbGl2ZV9jZXJ0czERMA8GA1UEAxQIbGl2ZV9hcGkxHDAaBgkqhkiG9w0BCQEWD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jUC7gytQRmxRuRybAKWdnvvWPhnhNXr04cHvTqDrof8f77BBcmanpG/7JnA5t/mv6/nNc2zGoFgoDP6g5pCetuwlUXA==-----END PKCS7-----">';
	html += '<input class="helpplzDonateBtn" type="submit" name="submit" value="donate"></div>';
	html += '<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1"></form>';

	$('#helpplzExt').html(html);
	
    // Use AJAX to search for the given string
	$('#helpplzExtSearchForm').submit(function() {
		return helpplz.search();
	});
	
    // Use AJAX post to add the plz account instead of a page reload
	$('#helpplzAddPlzF').submit(function() {
		return helpplz.addPlz();
	});
	
    // Show the add plz form when the user clicks the add button
	$('#helpplzAddPlz').click(function() {
		$('#helpplzAddPlzForm').toggle('fast');
	});
	
    // Delay loading until the user interacts with our button to save bandwidth
	$('#helpplzShower, .helpplzShowerLink').click(function() {
		if(!helpplz.hasLoadedFirstResults)
		{
			helpplz.hasLoadedFirstResults = true;
			helpplz.loadNext("http://helpplz.info/browsers/rest.php?" + helpplz.querystring);
		}
		$('#helpplzShower').toggle('fast');
		$('#helpplzExt').toggle('fast');
	});
	
    // Set up the UI for each account in our stored list
	if (helpplz.lstore['myList'] != null &&
	helpplz.lstore['myList'] != '') {
		$('#helpplzMyListMessage').hide();
		for (i in helpplz.lstore['myList'])
		{
			var item = helpplz.lstore['myList'][i];
			var newId = helpplz.generateUniqueId();
			$('#myList').append('<img id="myList'+newId+'" class="myListPlz" src="' + item.source + '" draggable="true" title="' + item.name + '"/>');
			helpplz.setupDraggable($('#myList'+newId).get(0), true);
		}
	}

    // Prevent document scrolling while the mouse is on our plugin. This allows
    // our AJAX to load without the user accidentally scrolling the page
	$('#helpplzContentParent').bind('mousewheel DOMMouseScroll', function(e) {
		var scrollTo = null;

		if (e.type == 'mousewheel') {
			scrollTo = (e.originalEvent.wheelDelta * -1);
		}
		else if (e.type == 'DOMMouseScroll') {
			scrollTo = 40 * e.originalEvent.detail;
		}

		if (scrollTo) {
			e.preventDefault();
			$(this).scrollTop(scrollTo + $(this).scrollTop());
		}
	});
    
    // Load new elements when the user gets to the bottom of the page
	$('#helpplzContentParent').scroll(function(){
		if (!helpplz.shownAllResults && !helpplz.loading && 
            $('#helpplzContentParent').scrollTop() == 
                $('#helpplzContent').height() - $('#helpplzContentParent').height() ) {
			helpplz.loading = true;
			helpplz.loadNext(helpplz.next);
		}
	});
	
	helpplz.setupDroppable('#myList', function() {
		// If we dragged an item from our list and dropped
		// it back in our list, return
		if (helpplz.dragData.fromMyList)
			return;
		
		var listData = helpplz.lstore['myList'];		
		if (listData == null || listData == '') {
			listData = new Array();
			$('#helpplzMyListMessage').hide();
		}
		// If the plz is already in our list, return
		for (var i=0;i<listData.length;i++)
		{
			if(listData[i].name == helpplz.dragData.name)
				return;
		}
		listData[listData.length] = {
			name: helpplz.dragData.name,
			source: helpplz.dragData.source
		};
		helpplz.lstore['myList'] = listData;
		helpplz_browser.save(helpplz.lstore);

		var newId = helpplz.generateUniqueId()
		$('#myList').append('<img id="myList'+newId+'" class="myListPlz" draggable="true" src="' + helpplz.dragData.source + '" title="' + helpplz.dragData.name + '"/>')
		helpplz.setupDraggable($('#myList' + newId).get(0), true);
	});
	
	helpplz.setupAvatarsForDragging();
});